import { openLoading } from "@/functions";
import { closeToast } from "vant";
import { ref } from "vue";

export const useSourceLoading = (finished: () => void, sourceCount: number = 0) => {
    const toast = openLoading();

    const num = ref(0);
    const isFinished = ref(false);
    toast.message = '加载中 0%';

    const render = () => {
        toast.message = `加载中 ${Math.floor(num.value / sourceCount * 100)}%`;
    }

    const close = () => {
        isFinished.value = true;
        closeToast();
        finished();
    }

    return {
        num,
        isFinished,
        setCurrent: (current: number) => {
            if (isFinished.value) {
                return;
            }

            num.value = Math.min(Math.floor(current), sourceCount);
        },

        setCount: (count: number) => {
            sourceCount = count;
            isFinished.value = false;
        },

        renderMessage: render,
        closeMessage: close
    }
}